from odoo import models, api


class MesStation(models.Model):
    _inherit = 'work.station'

    def cron_all(self):
        records = self.env['work.station'].sudo().search([])
        for rec in records:
            rec.station_upload_mes()

    @api.model_create_multi
    def create(self, vals_list):
        result = super().create(vals_list)
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            for rec in result:
                rec.with_delay().station_upload_mes()
        return result

    def write(self, vals):
        res = super().write(vals)
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            self.with_delay().station_upload_mes()
        return res

    def station_upload_mes(self):
        """
        工站上传 MES 系统
        """
        station_list = []
        for index, record in enumerate(self):
            pro_list = []
            for process in record.center_ids:
                pro_list.append({
                    "wp_code": process.code,
                    "remark": process.name
                })
            station_list.append({
                "org_id": "0001",
                "bs_process_code": record.code,
                "bs_process_name": record.name,
                "seq": index,
                "remark": "0",
                "bs_process_dt": pro_list
            })
        data = {
            "docType": "BS_PROCESS",
            "updateType": "UPDATE",
            "data": station_list
        }
        self.env['s.mes.upload'].upload_data(data=data)
